<?php
$className = "Member";
@include_once "installableInterface.inc";
/*
 * All operations concerning a single user
 * are to be handled by the User class.
 */
class Member implements Installable {
    private $db = null;
    /**
     * The minimal constructor expects at least a Database object.
     *
     * @param Database $db
     */
    public function __construct($db) {
        $this->db = $db;
    }

    /**
     * If the table exists it can be dropped in case
     * a reinstallation is neccessary for instance.
     * @param <link identifier> $db is the database handle.
     */
    public function dropTable() {
        $sql = "DROP TABLE IF EXISTS Members";
        $rs = $this->db->executeSQL($sql);
    }

    /**
     * Initially creates the table when the database is installed.
     * @param <link identifier> $db is the database handle.
     */
    public function createTable() {
        $this->dropTable();
        $sql = "
            CREATE TABLE  `Members` (
              `ID` int(11) NOT NULL AUTO_INCREMENT,
              `userID` int(11) NOT NULL DEFAULT '0',
              `groupID` int(11) NOT NULL DEFAULT '0',
              PRIMARY KEY (`ID`),
              UNIQUE KEY `memK` (`userID`,`groupID`)
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1
        ";
        $rs = $this->db->executeSQL($sql);
        if(!$rs)
            return(false);
        return(true);
    }
    public function insertInitialData() {
    }
    /**
     * Tests if a membership for the user exists for the selected group.
     * 
     * @param <User> $user:     the user that should be connected to the group.
     * @param <Group> $group:    the group that the user should be connected to. 
     */
    public function testMembership($user,$group) {
        $sql =  "SELECT * FROM Memberships WHERE UserID='" + $user->getID() + "'" +
                " AND GroupID='" + $group->getID() + "'";
        $this->db->getResult($sql);
        if($db)
            return(true);
        return(false);
    }
    /**
     * Establishes a membership for the user for the selected group if none exists.
     * 
     * @param <User> $user:     the user that should be connected to the group.
     * @param <Group> $group:    the group that the user should be connected to. 
     */
    public function createMembership($user,$group) {
        if(!testMembership($test,$group)) {
            $sql = "INSERT INTO Memberships (userID,groupID)
                    VALUES(" + $user->getID() + "," + $group->getID() + ")";
            $this->db->executeSQL($sql);
        }
    }
}
?>
